package com.plian.system.service.bpa.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.Tools.CollectionUtil;
import com.plian.Tools.StringUtil;
import com.plian.system.constant.bpa.OperatingPerformanceConstant;
import com.plian.system.dto.pf.OperatingPerformanceReportDTO;
import com.plian.system.dto.pf.PerformanceReportDTO;
import com.plian.system.entity.bpa.*;
import com.plian.system.entity.im.BaseInvestmentPlan;
import com.plian.system.entity.pf.*;
import com.plian.system.mapper.bpa.BpaIndustryStandardConfigMapper;
import com.plian.system.mapper.pf.BusinessReplenishMapper;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.bpa.*;
import com.plian.system.service.im.IBaseInvestmentPlanService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 经营业绩考核补充表 服务实现类
 *
 * @author
 * @since 2019-09-27
 */
@Slf4j
@Service
@AllArgsConstructor
public class OperatingPerformanceServiceImpl extends BaseServiceImpl<BusinessReplenishMapper, BusinessReplenish> implements IOperatingPerformanceService {


    private IFormCodeService formCodeService;

    private OrgzationService orgzationService;


    @Resource
    private BpaIndustryStandardConfigMapper standardConfigMapper;

    private final IBusinessAssessmentScoreService businessAssessmentScoreService;

    private final IBusinessAssessmentScoreDynamicService businessAssessmentScoreDynamicService;

    private final IBusinessAssessmentGearService businessAssessmentGearService;

    private final IBusinessAssessmentService businessAssessmentService;

    private final IBusinessAssessmentGearDynamicService businessAssessmentGearDynamicService;

    private final IBaseInvestmentPlanService baseInvestmentPlanService;

    /**
     * @param businessReplenishDTO
     * @return com.plian.system.model.R<com.plian.system.vo.report.ReportReturnVO>
     **/
//    @Override TODO DEL
//    public R<ReportReturnVO> summary(BusinessReplenishDTO businessReplenishDTO) {
//
//        if (StringUtil.isBlank(businessReplenishDTO.getFillingMonth())) {
//            businessReplenishDTO.setFillingMonth(DateUtil.format(DateUtil.now(), DateUtil.PATTERN_MONTH));
//        }
//        if (CollectionUtil.isEmpty(businessReplenishDTO.getFillingUnitIds())) {
//            return new R(CustomCode.builder().message("填报单位为空").code(1999).success(false).build());
//        }
//        String fillingUnitId = businessReplenishDTO.getFillingUnitIds().get(0);
//        String fillingYear = businessReplenishDTO.getFillingMonth();
//        //1 查询经营业绩考核主表
//        List<BaseBusinessIndicators> baseBusinessIndicatorsList = baseBusinessIndicatorsService.list(new LambdaQueryWrapper<BaseBusinessIndicators>()
//                .eq(BaseBusinessIndicators::getFillingYear, fillingYear)
//                .eq(BaseBusinessIndicators::getFillingUnitId, fillingUnitId)
//                .orderByDesc(BaseBusinessIndicators::getCreateTime));
//        if (CollectionUtil.isEmpty(baseBusinessIndicatorsList)) {
//            return new R(CustomCode.builder().message("该单位经营业绩考核表数据未填报").code(1999).success(false).build());
//        }
//        BaseBusinessIndicators baseBusinessIndicators = baseBusinessIndicatorsList.get(0);
//        //2 查询经营业绩考核指标表
//        List<BusinessIndicators> businessIndicators = businessIndicatorsService.list(new LambdaQueryWrapper<BusinessIndicators>()
//                .eq(BusinessIndicators::getBaseBusinessIndicatorsId, baseBusinessIndicators.getId()));
//        List<BusinessIndicatorsVO> voList = businessIndicatorsWrapper.entityToVO(businessIndicators);
//        if (CollectionUtil.isEmpty(voList)) {
//            return new R(CustomCode.builder().message("该单位经营业绩考核表数据未填报!").code(1999).success(false).build());
//        }
//
//        /**
//         * 3、确定该公司是那个行业和指标类型（行业标准配置）
//         **/
////        String industryCode = getUnitIndustryStandardConfig(fillingYear, fillingUnitId);
////        if (StringUtil.isEmpty(industryCode)) {
////            return new R(CustomCode.builder().message("该单位未配置行业标准").code(1999).success(false).build());
////        }
//        List<OperatingPerformanceReportVO> results = new ArrayList<>();
//        Long baseId = baseBusinessIndicators.getId();
//        List<AppraisalIndex> appraisalIndicesList = appraisalIndexMapper.selectList(new LambdaQueryWrapper<AppraisalIndex>().eq(AppraisalIndex::getType, "1")
//                .eq(AppraisalIndex::getFlag, "0"));
//        //配置主表 6个指标
//        List<BpaFinancialPerformance> bpaFinancialPerformances = bpaFinancialPerformanceMapper.selectList(null);
//        //确定在那个档位
//        List<BpaFinancialPerformanceGear> bpaFinancialPerformanceGears = performanceGearMapper.selectList(null);
//        //计分配置情况
//        List<BpaIndustryCreditConfig> bpaIndustryCreditConfigs = industryCreditConfigMapper.selectList(null);
//
//        for (AppraisalIndex appraisalIndex : appraisalIndicesList) {
//
//            //分别判断每个指标是得到数值
//            OperatingPerformanceReportDTO businessIndicatorsReportDTO = null;
//            List<OperatingPerformanceReportDTO> performanceReportValues = businessIndicatorsMapper.selectBusinessIndicators(baseId, appraisalIndex.getId());
//            if (CollectionUtil.isNotEmpty(performanceReportValues)) {
//                businessIndicatorsReportDTO = performanceReportValues.get(0);
//            }
//
//            //指标权重
//            BigDecimal indicatorsWeight = new BigDecimal(0);
//            //基准值
//            BigDecimal baseline = new BigDecimal(0);
//            //目标值
//            BigDecimal target = new BigDecimal(0);
//            //对比目标值
//            BigDecimal basicTarget = new BigDecimal(0);
//            //完成值
//            BigDecimal completeValue = new BigDecimal(0);
//            //分项得分
//            BigDecimal componentScores = new BigDecimal(0);
//            //折合得分 =  分项得分 * 权重
//            BigDecimal orScores = new BigDecimal(0);
//
//            if (businessIndicatorsReportDTO != null) {
//                indicatorsWeight = businessIndicatorsReportDTO.getIndicatorsWeight();
//                baseline = businessIndicatorsReportDTO.getBaseline();
//                target = businessIndicatorsReportDTO.getTarget();
//                basicTarget = businessIndicatorsReportDTO.getBasicTarget();
//
//            }
//            //查询市国资委审核数年度
//            BusinessAudit businessAudit = businessAuditService.getOne(new LambdaQueryWrapper<BusinessAudit>().eq(BusinessAudit::getBaseBusinessAuditId, baseId));
//            if (CollectionUtil.isNotEmpty(bpaFinancialPerformances)) {
//                try {
//                    if (businessAudit != null) {
//                        //完成值=国资审核数
//                        completeValue = businessAudit.getAuditSum();
//                    }
//                    //标准类型
//                    String standardCode = getCurrAppraisalIndexStandardConfig(appraisalIndex.getId(), fillingYear);
//                    if (StringUtil.isEmpty(standardCode)) {
//                        throw new MyRuntimeException(new ObjResult("未查询到当前指标-标准类型！"));
//                    }
//
//                    //分项得分
//                    BigDecimal currorComponentScores = makeSureScores(completeValue, bpaFinancialPerformanceGears, bpaIndustryCreditConfigs,
//                            bpaFinancialPerformances, null, standardCode, appraisalIndex, businessIndicatorsReportDTO);
//                    if (currorComponentScores != null) {
//                        componentScores = currorComponentScores;
//                    }
//                } catch (Exception e) {
//                    log.error("折合得分计算出错..." + e.getStackTrace());
//                }
//
//            }
//            //折合得分
//            orScores = componentScores.multiply(indicatorsWeight);
//
//            OperatingPerformanceReportVO operatingPerformanceReportVO = OperatingPerformanceReportVO.builder()
//                    .indicatorsCategoryName(appraisalIndex.getName())
//                    .indicatorsCategoryId(appraisalIndex.getId())
//                    .indicatorsWeight(indicatorsWeight)
//                    .baseline(baseline)
//                    .target(target)
//                    .basicTarget(basicTarget)
//                    .completeValue(completeValue)
//                    .componentScores(componentScores)
//                    .orScores(orScores).build();
//            results.add(operatingPerformanceReportVO);
//
//        }
//
//        //header
//        ReportVO reportVO = new ReportVO();
//        reportVO
//                .addHeader(HeaderVO.builder().key("indicatorsCategoryName").title("指标名称").build())
//                .addHeader(HeaderVO.builder().key("indicatorsWeight").title("指标权重").build())
//                .addHeader(HeaderVO.builder().key("baseline").title("基准值").build())
//                .addHeader(HeaderVO.builder().key("target").title("(对标)目标值").build())
//                .addHeader(HeaderVO.builder().key("basicTarget").title("基本目标值").build())
//                .addHeader(HeaderVO.builder().key("completeValue").title("完成值").build())
//                .addHeader(HeaderVO.builder().key("componentScores").title("分项得分").build())
//                .addHeader(HeaderVO.builder().key("orScores").title("折合得分").build());
//
//        reportVO.setData(results);
//        ReportReturnVO reportReturnVO = new ReportReturnVO();
//        reportReturnVO.setGrids(reportVO);
//        R<ReportReturnVO> obj = new R<>(CommonCode.SUCCESS);
//        obj.setPageData(reportReturnVO);
//        return obj;
//    }


//    /**
//     * 计算折合得分
//     *
//     * @param completeValue                当前判断的值 此时为完成值（审核数），可传其它值
//     * @param bpaFinancialPerformances     配置中所有主表配置信息
//     * @param bpaFinancialPerformanceGears 配置中所有档位配置信息
//     * @param bpaIndustryCreditConfigs     配置中所有得分配置信息
//     * @param industryCode                 行业类型
//     * @param standardCode                 标准类型
//     * @param appraisalIndex               当前指标信息
//     * @param businessIndicatorsReportDTO  当前指标信息
//     * @return java.math.BigDecimal
//     **/
//    @Override TODO DEL
//    public BigDecimal makeSureScores(BigDecimal completeValue, List<BpaFinancialPerformanceGear> bpaFinancialPerformanceGears,
//                                     List<BpaIndustryCreditConfig> bpaIndustryCreditConfigs, List<BpaFinancialPerformance> bpaFinancialPerformances,
//                                     String industryCode, String standardCode, AppraisalIndex appraisalIndex,
//                                     OperatingPerformanceReportDTO businessIndicatorsReportDTO) {
//        if (completeValue == null) {
//            log.info("error:比较值不能为空！");
//            return null;
//        }
//        /**
//         * 根据指标id，配置主表找到该指标 =》确定值
//         **/
//        List<BpaFinancialPerformance> performanceList = bpaFinancialPerformances.stream().filter(
//                item -> item.getIndicatorsId().equals(appraisalIndex.getId().toString()) && item.getDictIndicatorsCode().equals(standardCode)).collect(Collectors.toList());
//        if (CollectionUtil.isEmpty(performanceList)) {
//            log.info("info:未配置该指标的配置信息...");
//            return null;
//        }
//        BpaFinancialPerformance bpaFinancialPerformance = performanceList.get(0);
//        /**
//         * 判断档位下面是否有该单位的行业类型
//         */
//        List<BpaFinancialPerformanceGear> gearList = bpaFinancialPerformanceGears.stream().filter(
//                item -> item.getFpid().equals(bpaFinancialPerformance.getId()) && item.getIndustryCode().equals(industryCode)).collect(Collectors.toList());
//        BpaFinancialPerformanceGear performanceGear = gearList.get(0);
//        //档位配置信息
//        List<BpaIndustryCreditConfig> creditConfigList = bpaIndustryCreditConfigs.stream().filter(
//                item -> item.getFpid().equals(bpaFinancialPerformance.getId())).collect(Collectors.toList());
//
//
//        /**
//         * 根据标准类型，行业类型，判断当前指标处于那个档位下
//         * 标准型：比较优秀值-较差值
//         * 自定行：比较所有
//         **/
//        int colNum = judgeGear(performanceGear, standardCode, completeValue);
//        if (colNum == -1) {
//            log.info("info:该数值下未查询到符合的档位信息...");
//            return null;
//        }
//        //查询当前指标下的值
//        BigDecimal finalCredit = getFinalCredit(completeValue, creditConfigList, colNum, businessIndicatorsReportDTO, bpaFinancialPerformance.getScoreStandard());
//        return finalCredit.setScale(4, BigDecimal.ROUND_HALF_UP);
//    }

    /**
     * @param completeValue               自定义值 传过来的
     * @param creditConfigList            计分配置集合
     * @param col                         处于那一列
     * @param businessIndicatorsReportDTO 该指标的值信息
     * @param scoreStandard               计分标准
     * @return java.math.BigDecimal
     **/
    private BigDecimal getFinalCredit(BigDecimal completeValue, List<BpaIndustryCreditConfig> creditConfigList, int col,
                                      OperatingPerformanceReportDTO businessIndicatorsReportDTO, String scoreStandard) {

        BigDecimal value = new BigDecimal(0);

        for (BpaIndustryCreditConfig config : creditConfigList) {
            //当前比较类型  大于/大于等于/小于/区间
            String compareTypeCode = config.getCompareTypeCode();
            //当前对比标准  激励目标值/基本目标值/自定义/基准值
            String compareStandardCode = config.getCompareStandardCode();
            //当前行值
            BigDecimal currRowCreditVal = getCurrRowCreditVal(config, col);

            if (OperatingPerformanceConstant.BPA_COMPARE_STANDARD_TARGET.equals(compareStandardCode)) {
                //激励目标值
                BigDecimal target = businessIndicatorsReportDTO.getTarget();
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_A.equals(compareTypeCode) && completeValue.compareTo(target) == 1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_B.equals(compareTypeCode) && completeValue.compareTo(target) > -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_C.equals(compareTypeCode) && completeValue.compareTo(target) == -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_D.equals(compareTypeCode) && completeValue.compareTo(target) == 1
                        && completeValue.compareTo(target) == -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }

            } else if (OperatingPerformanceConstant.BPA_COMPARE_STANDARD_BASIC_TARGET.equals(compareStandardCode)) {
                //基本目标值
                BigDecimal basicTarget = businessIndicatorsReportDTO.getBasicTarget();
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_A.equals(compareTypeCode) && completeValue.compareTo(basicTarget) == 1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_B.equals(compareTypeCode) && completeValue.compareTo(basicTarget) > -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_C.equals(compareTypeCode) && completeValue.compareTo(basicTarget) == -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_D.equals(compareTypeCode) && completeValue.compareTo(basicTarget) == 1
                        && completeValue.compareTo(basicTarget) == -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }

            } else if (OperatingPerformanceConstant.BPA_COMPARE_STANDARD_CUSTOM.equals(compareStandardCode)) {
                String customValue = config.getCustomValue();
                BigDecimal currCus = changeScoreStand(customValue);
                BigDecimal currCompleteValue = completeValue.multiply(currCus);

                //自定义
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_A.equals(compareTypeCode) && completeValue.compareTo(currCompleteValue) == 1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_B.equals(compareTypeCode) && completeValue.compareTo(currCompleteValue) > -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_C.equals(compareTypeCode) && completeValue.compareTo(currCompleteValue) == -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_D.equals(compareTypeCode) && completeValue.compareTo(currCompleteValue) == 1
                        && currRowCreditVal.compareTo(completeValue) == -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }

            } else if (OperatingPerformanceConstant.BPA_COMPARE_STANDARD_BASLINE.equals(compareStandardCode)) {
                //基准值
                BigDecimal baseline = businessIndicatorsReportDTO.getBaseline();
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_A.equals(compareTypeCode) && completeValue.compareTo(baseline) == 1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_B.equals(compareTypeCode) && completeValue.compareTo(baseline) > -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_C.equals(compareTypeCode) && completeValue.compareTo(baseline) == -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }
                if (OperatingPerformanceConstant.BPA_COMPARE_TYPE_D.equals(compareTypeCode) && completeValue.compareTo(baseline) == 1
                        && completeValue.compareTo(baseline) == -1) {
                    return currRowCreditVal.multiply(changeScoreStand(scoreStandard));
                }

            }

        }
        return value;
    }

    /**
     * 取出当前行的值
     *
     * @param config 当前行配置信息
     * @param col    列数
     * @return java.math.BigDecimal
     **/
    private BigDecimal getCurrRowCreditVal(BpaIndustryCreditConfig config, int col) {
        switch (col) {
            case 1:
                return gearBigDecimalUtil(config.getDw1());
            case 2:
                return gearBigDecimalUtil(config.getDw2());
            case 3:
                return gearBigDecimalUtil(config.getDw3());
            case 4:
                return gearBigDecimalUtil(config.getDw4());
            case 5:
                return gearBigDecimalUtil(config.getDw5());
            case 6:
                return gearBigDecimalUtil(config.getDw6());
            case 7:
                return gearBigDecimalUtil(config.getDw7());
            case 8:
                return gearBigDecimalUtil(config.getDw8());
            case 9:
                return gearBigDecimalUtil(config.getDwn());
            default:
                return new BigDecimal(0);
        }
    }


    /**
     * 判断年份去查询单位的标准类型和行业类型
     *
     * @param year
     * @return
     */
    @Override
    public BpaIndustryStandardConfig getUnitIndustryStandardConfig(String year, String orgId) {
        List<BpaIndustryStandardConfig> bpaIndustryStandardConfigList = standardConfigMapper.selectList(new LambdaQueryWrapper<BpaIndustryStandardConfig>().
                eq(BpaIndustryStandardConfig::getIsYear, year));
        if (CollectionUtil.isEmpty(bpaIndustryStandardConfigList)) {
            return null;
        }
        List<BpaIndustryStandardConfig> currConfigList = bpaIndustryStandardConfigList.stream().filter(item
                -> item.getSuitableUnitId().contains(orgId)
        ).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(currConfigList)) {
            return null;
        }
        BpaIndustryStandardConfig standardConfig = currConfigList.get(0);
        return standardConfig;
    }

//    /** TODO DEL
//     * 得到当前指标的，对应年份下的标准类型
//     *
//     * @param indicatorsId
//     * @return java.lang.String
//     **/
//    @Override
//    public String getCurrAppraisalIndexStandardConfig(Long indicatorsId, String year) {
//        List<BusinessAssessment> list = businessAssessmentService.list(Wrappers.<BusinessAssessment>lambdaQuery()
//                .eq(BusinessAssessment::getIndicatorsId, indicatorsId)
//                .eq(BusinessAssessment::getIsYear, year)
//                .eq(BusinessAssessment::getEnabled, 1));
//        if (CollectionUtil.isNotEmpty(list)) {
//            return list.get(0).getDictIndicatorsCode();
//        }
//        return null;
//    }

    /**
     * 行业标准下-》返回当前指标处于配置第几列
     *
     * @param performanceGear    该指标的档位信息（唯一）
     * @param dictIndicatorsCode 标准类型
     * @param completeValue      值
     * @return int
     **/
    private int judgeGear(BpaFinancialPerformanceGear performanceGear, String dictIndicatorsCode, BigDecimal completeValue) {
        if (OperatingPerformanceConstant.BPA_STANDARD_TYPE_INDUSTY.equals(dictIndicatorsCode)) {
            //行业标准型，将优秀值-5项 较差值存入，确定哪一列 dw4-dw8
            BigDecimal dw4 = gearBigDecimalUtil(performanceGear.getDw4());
            BigDecimal dw5 = gearBigDecimalUtil(performanceGear.getDw5());
            BigDecimal dw6 = gearBigDecimalUtil(performanceGear.getDw6());
            BigDecimal dw7 = gearBigDecimalUtil(performanceGear.getDw7());
            BigDecimal dw8 = gearBigDecimalUtil(performanceGear.getDw8());
            if (completeValue.compareTo(dw4) > -1 && completeValue.compareTo(dw5) == -1) {
                return 4;
            } else if (completeValue.compareTo(dw5) > -1 && completeValue.compareTo(dw6) == -1) {
                return 5;
            } else if (completeValue.compareTo(dw6) > -1 && completeValue.compareTo(dw7) == -1) {
                return 6;
            } else if (completeValue.compareTo(dw7) > -1 && completeValue.compareTo(dw8) == -1) {
                return 7;
            } else if (completeValue.compareTo(dw8) > -1) {
                return 8;
            }
        } else if (OperatingPerformanceConstant.BPA_STANDARD_TYPE_CUSTOM.equals(dictIndicatorsCode)) {
            List<BigDecimal> dw1List = gearStringUtil(performanceGear.getDw1());
            List<BigDecimal> dw2List = gearStringUtil(performanceGear.getDw2());
            List<BigDecimal> dw3List = gearStringUtil(performanceGear.getDw3());
            List<BigDecimal> dw4List = gearStringUtil(performanceGear.getDw4());
            List<BigDecimal> dw5List = gearStringUtil(performanceGear.getDw5());
            List<BigDecimal> dw6List = gearStringUtil(performanceGear.getDw6());
            List<BigDecimal> dw7List = gearStringUtil(performanceGear.getDw7());
            List<BigDecimal> dw8List = gearStringUtil(performanceGear.getDw8());
            List<BigDecimal> dw9List = gearStringUtil(performanceGear.getDwn());

            if (completeValue.compareTo(dw1List.get(0)) > -1 && completeValue.compareTo(dw1List.get(1)) < 1) {
                return 1;
            } else if (completeValue.compareTo(dw2List.get(0)) > -1 && completeValue.compareTo(dw2List.get(1)) < 1) {
                return 2;
            } else if (completeValue.compareTo(dw3List.get(0)) > -1 && completeValue.compareTo(dw3List.get(1)) < 1) {
                return 3;
            } else if (completeValue.compareTo(dw4List.get(0)) > -1 && completeValue.compareTo(dw4List.get(1)) < 1) {
                return 4;
            } else if (completeValue.compareTo(dw5List.get(0)) > -1 && completeValue.compareTo(dw5List.get(1)) < 1) {
                return 5;
            } else if (completeValue.compareTo(dw6List.get(0)) > -1 && completeValue.compareTo(dw6List.get(1)) < 1) {
                return 6;
            } else if (completeValue.compareTo(dw7List.get(0)) > -1 && completeValue.compareTo(dw7List.get(1)) < 1) {
                return 7;
            } else if (completeValue.compareTo(dw8List.get(0)) > -1 && completeValue.compareTo(dw8List.get(1)) < 1) {
                return 8;
            } else if (completeValue.compareTo(dw9List.get(0)) > -1 && completeValue.compareTo(dw9List.get(1)) < 1) {
                return 9;
            }
        }
        return -1;
    }

    /**
     * 标准类型下档位转化值
     * 计分值转化
     **/
    private BigDecimal gearBigDecimalUtil(String dwValue) {
        if (StringUtil.isNotBlank(dwValue)) {
            return new BigDecimal(dwValue);
        }
        return new BigDecimal(0);
    }

    /**
     * 自定类型下，档位值是区间
     * 转换
     *
     * @param dwValue
     * @return java.math.BigDecimal
     **/
    private List<BigDecimal> gearStringUtil(String dwValue) {
        List<BigDecimal> result = new LinkedList<>();
        BigDecimal v1 = new BigDecimal(0);
        BigDecimal v2 = new BigDecimal(0);
        if (StringUtil.isNotBlank(dwValue) && dwValue.contains("-")) {
            String[] values = dwValue.split("-");
            v1 = new BigDecimal(values[0]);
            v2 = new BigDecimal(values[1]);
        }
        result.add(v1);
        result.add(v2);
        return result;
    }

    /**
     * 将计分标准转为小数
     *
     * @param value 计分标准
     * @return double
     **/
    private BigDecimal changeScoreStand(String value) {
        //百分比转换为小数
        if (value.contains("%")) {
            value = value.replace("%", "");
        }
        Double f = Double.valueOf(value) / 100;
        return new BigDecimal(f);

    }

    /**
     * @param completeValue
     * @param businessAssessmentGearList  所有的档位
     * @param businessAssessmentScoreList 所有的计分配置
     * @param businessAssessmentList      所有的配置主表
     * @param appraisalIndex
     * @return
     */
    @Override
    public BigDecimal newMakeSureScores(String orgId, String year, BusinessAudit businessAudit, BigDecimal completeValue, List<BusinessAssessmentGear> businessAssessmentGearList, List<BusinessAssessmentScore> businessAssessmentScoreList,
                                        List<BusinessAssessment> businessAssessmentList, BpaIndustryStandardConfig unitIndustryStandardConfig, AppraisalIndex appraisalIndex) {

        PerformanceReportDTO dto = new PerformanceReportDTO();
        dto.setOrgId(orgId);
        dto.setYear(year);
        String industryCode = unitIndustryStandardConfig.getIndustryTypeCode();

        //根据指标id，配置主表找到该指标 =》确定值
//        List<BusinessAssessment> assessmentList = businessAssessmentList.stream().filter(
//                item -> item.getIndicatorsId().equals(appraisalIndex.getId().toString())
//                        && item.getDictIndicatorsCode().equals(standardCode)).collect(Collectors.toList());
        //行业型和标准型运算一样
        List<BusinessAssessment> assessmentList = businessAssessmentList.stream().filter(
                item -> item.getIndicatorsId().equals(appraisalIndex.getId().toString())).collect(Collectors.toList());

        if (CollectionUtil.isEmpty(assessmentList)) {
            log.info("info:未配置该指标的配置信息...");
            return null;
        }
        BusinessAssessment businessAssessment = assessmentList.get(0);
        String standardCode = businessAssessment.getDictIndicatorsCode();

        //档位类型  139009全行业,全行业的时候取全行业，没有就取自己
        List<BusinessAssessmentGear> gearList = new ArrayList<>();
        List<BusinessAssessmentGear> allIndustryTypeList = businessAssessmentGearList.stream().filter(e -> e.getIndustryTypeCode().equals("139009") &&
                e.getBusinessAssessmentId().equals(businessAssessment.getId())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(allIndustryTypeList)) {
            gearList = allIndustryTypeList;
        } else {
            gearList = businessAssessmentGearList.stream().filter(
                    item -> item.getBusinessAssessmentId().equals(businessAssessment.getId()) &&
                            item.getIndustryTypeCode().equals(industryCode)).collect(Collectors.toList());
        }

        //计分配置信息
        List<BusinessAssessmentScore> scoreList = businessAssessmentScoreList.stream().filter(
                item -> item.getBusinessAssessmentId().equals(businessAssessment.getId())).collect(Collectors.toList());

        String name = appraisalIndex.getName();

        /**
         * 计算每个指标的档位和分数
         */
        switch (name) {
            case "净资产收益率":
                //配置中取档位
                return jzcValue(industryCode, businessAudit, completeValue, businessAssessment, gearList, scoreList);
            case "人均归母净利润":
                //档位按单位取
                return rjgmValue(dto, businessAudit, completeValue, businessAssessment, gearList, scoreList);
//            case "有效投资（含重大项目）":
//                //配置中取档位
//                List<BaseInvestmentPlan> list = baseInvestmentPlanService.list(Wrappers.<BaseInvestmentPlan>lambdaQuery()
//                        .eq(BaseInvestmentPlan::getFilingUnitId, dto.getOrgId()).eq(BaseInvestmentPlan::getFilingYear, dto.getYear())
//                        .eq(BaseInvestmentPlan::getStatus, FormStatusConstant.FINISH));
//                if (CollectionUtil.isNotEmpty(list)) {
//                    // 获取最新的 BaseInvestmentPlan 对象
//                    BaseInvestmentPlan latestPlan = list.stream()
//                            .max(Comparator.comparing(BaseInvestmentPlan::getCreateTime))
//                            .orElse(null);
//                    return yxtz(industryCode, latestPlan, businessAudit, completeValue, businessAssessment, gearList, scoreList);
//                }
//                return null;
            case "融资成本率":
                //未从后台配置中取
                return rzcbValue(industryCode, businessAudit, completeValue, businessAssessment, gearList, scoreList);
            case "成本费用占营业收入比重":
                //未从后台配置中取
                return cbfyzb(industryCode, businessAudit, completeValue, businessAssessment, gearList, scoreList);
            case "营业收入完成率":
                //根据单位取档位
                return yesrwc(industryCode, dto, businessAudit, completeValue, businessAssessment, gearList, scoreList);
            case "贸易类营业收入完成率":
                //贸易类只配一个档  需求确认了
                return mylYesrwc(industryCode, dto, businessAudit, completeValue, businessAssessment, gearList, scoreList);
            case "非贸易类营业收入完成率":
                //根据单位取档位
                return yesrwc(industryCode, dto, businessAudit, completeValue, businessAssessment, gearList, scoreList);
            case "建设项目概算节省率（超概率）":
                //只针对水务集团 直接=2
                return zdgcjsgs(dto, businessAudit, completeValue, businessAssessment, gearList, scoreList);
            default:
                return null;
        }
    }

    /**
     * 建设项目概算节省率（超概率）项目概算
     * 直接取格子里面的分数
     *
     * @param dto
     * @param businessAudit
     * @param completeValue
     * @param businessAssessment
     * @param gearList
     * @param scoreList
     * @return
     */
    public BigDecimal zdgcjsgs(PerformanceReportDTO dto, BusinessAudit businessAudit, BigDecimal completeValue, BusinessAssessment businessAssessment,
                               List<BusinessAssessmentGear> gearList, List<BusinessAssessmentScore> scoreList) {
        try {
            //只针对水务集团
            String name = orgzationService.getNameById(dto.getOrgId());
            if (name.contains("宁波市水务环境集团有限公司")) {
                //直接去第二档
                Integer index = 2;

                BigDecimal rate = new BigDecimal(businessAssessment.getScoreStandard()).divide(new BigDecimal(100));

                //大于
                Optional<BusinessAssessmentScore> score1 = scoreList.stream().filter(e -> e.getCompareTypeCode().equals("171001")).findFirst();
                if (score1.isPresent()) {
                    BusinessAssessmentScore businessAssessmentScore = score1.get();
                    String customValueStr = businessAssessmentScore.getCustomValue();
                    BigDecimal customValue = new BigDecimal(customValueStr);
                    if (completeValue.compareTo(customValue) >= 0) {

                        List<BusinessAssessmentScoreDynamic> dynamicList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                                .eq(BusinessAssessmentScoreDynamic::getScoreId, businessAssessmentScore.getId()).eq(BusinessAssessmentScoreDynamic::getDwIndex, index));
                        if (CollectionUtil.isNotEmpty(dynamicList)) {
                            BusinessAssessmentScoreDynamic businessAssessmentScoreDynamic = dynamicList.get(0);
                            if (StringUtil.isNotBlank(businessAssessmentScoreDynamic.getDwValue())) {
                                return new BigDecimal(businessAssessmentScoreDynamic.getDwValue());
                            }
                        }
                    }

                }
                //区间
                Optional<BusinessAssessmentScore> score2 = scoreList.stream().filter(e -> e.getCompareTypeCode().equals("171003")).findFirst();
                if (score2.isPresent()) {
                    BusinessAssessmentScore businessAssessmentScore = score2.get();
                    String customValueStr = businessAssessmentScore.getCustomValue();

                    String[] split = customValueStr.split(",");
                    BigDecimal customValueStart = new BigDecimal(split[0]);
                    BigDecimal customValueEnd = new BigDecimal(split[1]);

                    if (completeValue.compareTo(customValueStart) >= 0 && completeValue.compareTo(customValueEnd) <= 0) {
                        List<BusinessAssessmentScoreDynamic> dynamicList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                                .eq(BusinessAssessmentScoreDynamic::getScoreId, businessAssessmentScore.getId()).eq(BusinessAssessmentScoreDynamic::getDwIndex, index));
                        if (CollectionUtil.isNotEmpty(dynamicList)) {
                            BusinessAssessmentScoreDynamic businessAssessmentScoreDynamic = dynamicList.get(0);
                            if (StringUtil.isNotBlank(businessAssessmentScoreDynamic.getDwValue())) {
                                return new BigDecimal(businessAssessmentScoreDynamic.getDwValue());
                            }
                        }
                    }

                }
                //小于
                Optional<BusinessAssessmentScore> score3 = scoreList.stream().filter(e -> e.getCompareTypeCode().equals("171002")).findFirst();
                if (score3.isPresent()) {
                    BusinessAssessmentScore businessAssessmentScore = score3.get();
                    String customValueStr = businessAssessmentScore.getCustomValue();
                    BigDecimal customValue = new BigDecimal(customValueStr);
                    if (completeValue.compareTo(customValue) <= 0) {

                        List<BusinessAssessmentScoreDynamic> dynamicList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                                .eq(BusinessAssessmentScoreDynamic::getScoreId, businessAssessmentScore.getId()).eq(BusinessAssessmentScoreDynamic::getDwIndex, index));
                        if (CollectionUtil.isNotEmpty(dynamicList)) {
                            BusinessAssessmentScoreDynamic businessAssessmentScoreDynamic = dynamicList.get(0);
                            if (StringUtil.isNotBlank(businessAssessmentScoreDynamic.getDwValue())) {
                                return new BigDecimal(businessAssessmentScoreDynamic.getDwValue());
                            }
                        }
                    }

                }
            }
        } catch (Exception e) {
            log.error("error:建设项目概算节省率（超概率）计分失败！" + e);
        }
        return null;
    }

    /**
     * 贸易类营业收入完成率计算逻辑是 (（完成值-100）)/100
     * 计划营业收入
     *
     * @param dto
     * @param businessAudit
     * @param completeValue
     * @param businessAssessment
     * @param gearList
     * @param scoreList
     * @return
     */
    public BigDecimal mylYesrwc(String industryCode, PerformanceReportDTO dto, BusinessAudit businessAudit, BigDecimal completeValue, BusinessAssessment businessAssessment,
                                List<BusinessAssessmentGear> gearList, List<BusinessAssessmentScore> scoreList) {

        //贸易类只配一个档  需求确认了
        Integer index = 1;
        try {
            String scoreStandardUnit = businessAssessment.getScoreStandardUnit();
            BigDecimal rate = new BigDecimal(businessAssessment.getScoreStandard());

            Optional<BusinessAssessmentScore> scoreOptional1 = scoreList.stream().filter(item -> item.getCompareTypeCode().equals("171001")).findFirst();
            if (scoreOptional1.isPresent()) {
                BusinessAssessmentScore assessmentScore1 = scoreOptional1.get();

                BigDecimal val1 = completeValue.subtract(new BigDecimal(100));
                BigDecimal val2 = val1.divide(new BigDecimal(100), 4, RoundingMode.HALF_UP);


                List<BusinessAssessmentScoreDynamic> currentScoreDynamicsList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                        .eq(BusinessAssessmentScoreDynamic::getScoreId, assessmentScore1.getId()).eq(BusinessAssessmentScoreDynamic::getDwIndex, index));
                BusinessAssessmentScoreDynamic scoreDynamic = currentScoreDynamicsList.get(0);

                BigDecimal result = val2.multiply(new BigDecimal(scoreDynamic.getDwValue()));
                return result.setScale(4, RoundingMode.HALF_UP);
            }
            //小于
            Optional<BusinessAssessmentScore> scoreOptional3 = scoreList.stream().filter(item -> item.getCompareTypeCode().equals("171002")).findFirst();
            if (scoreOptional3.isPresent()) {
                BusinessAssessmentScore assessmentScore3 = scoreOptional3.get();

                BigDecimal val1 = completeValue.subtract(new BigDecimal(100));
                BigDecimal val2 = val1.subtract(new BigDecimal("0.3"));

                List<BusinessAssessmentScoreDynamic> currentScoreDynamicsList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                        .eq(BusinessAssessmentScoreDynamic::getScoreId, assessmentScore3.getId()).eq(BusinessAssessmentScoreDynamic::getDwIndex, index));
                BusinessAssessmentScoreDynamic scoreDynamic = currentScoreDynamicsList.get(0);

                BigDecimal result = val2.multiply(new BigDecimal(scoreDynamic.getDwValue()));
                return result.setScale(4, RoundingMode.HALF_UP);
            }
        } catch (Exception e) {
            log.error("error:贸易类营业收入完成率->营业收入完成率计分失败" + e);
        }
        return null;
    }

    /**
     * 营业收入完成率：计划营业收入
     * 非贸易类
     *
     * @param dto
     * @param businessAudit
     * @param completeValue
     * @param businessAssessment
     * @param gearList
     * @param scoreList
     * @return
     */
    public BigDecimal yesrwc(String industryCode, PerformanceReportDTO dto, BusinessAudit businessAudit, BigDecimal completeValue, BusinessAssessment businessAssessment,
                             List<BusinessAssessmentGear> gearList, List<BusinessAssessmentScore> scoreList) {

        String scoreStandardUnit = businessAssessment.getScoreStandardUnit();
        BigDecimal rate = new BigDecimal(businessAssessment.getScoreStandard());

        //若档位配置为空的话，则默认1列
        Integer index = getYysrwcOrgDw(dto);

        if (!Objects.isNull(index)) {
            try {
                Optional<BusinessAssessmentScore> scoreOptional1 = scoreList.stream().filter(item -> item.getCompareTypeCode().equals("171001")).findFirst();
                if (scoreOptional1.isPresent()) {
                    BusinessAssessmentScore assessmentScore1 = scoreOptional1.get();
                    String customValueStr = assessmentScore1.getCustomValue();
                    BigDecimal customValue = new BigDecimal(customValueStr);


                    List<BusinessAssessmentScoreDynamic> scoreDynamicsList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                            .eq(BusinessAssessmentScoreDynamic::getScoreId, assessmentScore1.getId()).eq(BusinessAssessmentScoreDynamic::getDwIndex, index));
                    BusinessAssessmentScoreDynamic businessAssessmentScoreDynamic = scoreDynamicsList.get(0);

                    //result = 大于+区间
                    BigDecimal result = BigDecimal.ZERO;
                    //大于150
                    if (completeValue.compareTo(customValue) >= 0) {
                        BigDecimal dwValue = new BigDecimal(businessAssessmentScoreDynamic.getDwValue());
                        BigDecimal val1 = (completeValue.subtract(customValue)).divide(rate, 4, RoundingMode.HALF_UP).multiply(dwValue).setScale(4, RoundingMode.HALF_UP);
                        result = result.add(val1);

                        //区间部
                        Optional<BusinessAssessmentScore> scoreOptional2 = scoreList.stream().filter(item -> item.getCompareTypeCode().equals("171003")).findFirst();
                        if (scoreOptional2.isPresent()) {
                            //区间部分
                            BusinessAssessmentScore assessmentScore2 = scoreOptional2.get();
                            String[] split = assessmentScore2.getCustomValue().split(",");
                            BigDecimal start = new BigDecimal(split[0]);
                            BigDecimal end = new BigDecimal(split[1]);

                            List<BusinessAssessmentScoreDynamic> currentScoreDynamicsList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                                    .eq(BusinessAssessmentScoreDynamic::getScoreId, assessmentScore2.getId()).eq(BusinessAssessmentScoreDynamic::getDwIndex, index));
                            BusinessAssessmentScoreDynamic scoreDynamic = currentScoreDynamicsList.get(0);

                            BigDecimal val2 = (end.subtract(start)).divide(rate, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(scoreDynamic.getDwValue()));
                            result = result.add(val2);
                        }

                        // return result.multiply(new BigDecimal(0.01)).setScale(4, RoundingMode.HALF_UP);
                        return result.setScale(4, RoundingMode.HALF_UP);
                    }
                }
                //区间情况
                Optional<BusinessAssessmentScore> scoreOptional2 = scoreList.stream().filter(item -> item.getCompareTypeCode().equals("171003")).findFirst();
                if (scoreOptional2.isPresent()) {
                    //区间部分
                    BusinessAssessmentScore assessmentScore2 = scoreOptional2.get();
                    String[] split = assessmentScore2.getCustomValue().split(",");
                    BigDecimal start = new BigDecimal(split[0]);
                    BigDecimal end = new BigDecimal(split[1]);

                    if (completeValue.compareTo(start) >= 0 && completeValue.compareTo(end) <= 0) {
                        List<BusinessAssessmentScoreDynamic> currentScoreDynamicsList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                                .eq(BusinessAssessmentScoreDynamic::getScoreId, assessmentScore2.getId()).eq(BusinessAssessmentScoreDynamic::getDwIndex, index));
                        BusinessAssessmentScoreDynamic scoreDynamic = currentScoreDynamicsList.get(0);

                        BigDecimal val2 = (completeValue.subtract(start)).divide(rate, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(scoreDynamic.getDwValue())).setScale(4, RoundingMode.HALF_UP);
                        return val2.setScale(4, RoundingMode.HALF_UP);
                    }
                }
                //小于
                Optional<BusinessAssessmentScore> scoreOptional3 = scoreList.stream().filter(item -> item.getCompareTypeCode().equals("171002")).findFirst();
                if (scoreOptional3.isPresent()) {
                    //区间部分
                    BusinessAssessmentScore assessmentScore3 = scoreOptional3.get();
                    String customValueStr = assessmentScore3.getCustomValue();
                    BigDecimal customValue = new BigDecimal(customValueStr);

                    List<BusinessAssessmentScoreDynamic> currentScoreDynamicsList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                            .eq(BusinessAssessmentScoreDynamic::getScoreId, assessmentScore3.getId()).eq(BusinessAssessmentScoreDynamic::getDwIndex, index));
                    BusinessAssessmentScoreDynamic scoreDynamic = currentScoreDynamicsList.get(0);

                    if (completeValue.compareTo(customValue) < 0) {
                        BigDecimal result = (customValue.subtract(completeValue)).multiply(new BigDecimal("0.1")).multiply(new BigDecimal(scoreDynamic.getDwValue())).setScale(4, RoundingMode.HALF_UP);
                        return result.setScale(4, RoundingMode.HALF_UP);
                    }
                }
            } catch (Exception e) {
                log.error("error:非贸易类营业收入完成率计分失败" + e);
            }

        }
        return null;
    }

    /**
     * 营业收入完成率 根据单位确定档位
     * 营业收入完成率各家档位取数：需求提供的
     * 演艺 1档
     * 水务 1档
     * 文旅 2档
     * 商贸 2档
     * 交投 6档
     * 城投 1档
     * 开投 1档
     * 工投 4档
     * 广电 1档
     * 报业 1档
     * 宁兴 1档
     * 轨道 1档
     * 通商 4档
     *
     * @param dto
     * @return
     */
    private Integer getYysrwcOrgDw(PerformanceReportDTO dto) {
        String orgId = dto.getOrgId();
        String orgName = orgzationService.getNameById(orgId);
        if (orgName.equals("宁波市演艺集团有限公司") || orgName.equals("宁波广电传媒集团有限公司") || orgName.equals("宁波报业传媒集团有限公司")) {
            return 1;
        } else if (orgName.equals("宁波文旅会展集团有限公司") || orgName.equals("宁波市商贸集团有限公司") || orgName.equals("宁兴集团(宁波)有限公司")) {
            return 2;
        } else if (orgName.equals("宁波市水务环境集团有限公司") || orgName.equals("宁波市轨道交通集团有限公司")) {
            return 3;
        } else if (orgName.equals("宁波城建投资集团有限公司") || orgName.equals("宁波工业投资集团有限公司") || orgName.equals("宁波通商控股集团有限公司")) {
            return 4;
        } else if (orgName.equals("宁波交通投资集团有限公司") || orgName.equals("宁波开发投资集团有限公司")) {
            return 6;
        }
        return null;
    }

    /**
     * 人均归母分档：需求提供的
     * 轨道 3档
     * 宁兴 3档
     * 城投 2档
     * 开投 1档
     * 交投 4档
     * 工投 1档
     * 商贸 2档
     * 文旅 2档
     * 演艺 6档
     * 水务 3档
     * 广电 4档
     * 报业 2档
     *
     * @param dto
     * @return
     */
    private Integer getRjgmOrgDw(PerformanceReportDTO dto) {
        String orgId = dto.getOrgId();
        String orgName = orgzationService.getNameById(orgId);
        if (orgName.equals("宁波开发投资集团有限公司") || orgName.equals("宁波工业投资集团有限公司")) {
            return 1;
        } else if (orgName.equals("宁波城建投资集团有限公司") || orgName.equals("宁波市商贸集团有限公司") || orgName.equals("宁波文旅会展集团有限公司") || orgName.equals("宁波报业传媒集团有限公司")) {
            return 2;
        } else if (orgName.equals("宁波市轨道交通集团有限公司") || orgName.equals("宁兴集团(宁波)有限公司") || orgName.equals("宁波市水务环境集团有限公司")) {
            return 3;
        } else if (orgName.equals("宁波交通投资集团有限公司") || orgName.equals("宁波广电传媒集团有限公司")) {
            return 4;
        } else if (orgName.equals("宁波市演艺集团有限公司")) {
            return 6;
        }
        return null;
    }

    /**
     * 成本费用占比：完成值 需求说没有档位配置
     * <p>
     * （基准值-完成值）/（基准值*0.05）*具体加减分
     *
     * @param businessAudit
     * @param completeValue
     * @param businessAssessment
     * @param gearList
     * @param scoreList
     * @return
     */
    public BigDecimal cbfyzb(String industryCode, BusinessAudit businessAudit, BigDecimal completeValue, BusinessAssessment businessAssessment,
                             List<BusinessAssessmentGear> gearList, List<BusinessAssessmentScore> scoreList) {

        try {
            if (!Objects.isNull(businessAudit)) {
                BigDecimal rate = new BigDecimal(businessAssessment.getScoreStandard()).divide(new BigDecimal(100));
                //激励目标值
                BigDecimal target = businessAudit.getTarget();
                //基本目标值
                BigDecimal basicTarget = businessAudit.getBasicTarget();
                //基准值
                BigDecimal baseline = businessAudit.getBaseline();

                BigDecimal val1 = baseline.subtract(completeValue);
                BigDecimal val2 = baseline.multiply(rate);
                BigDecimal val3 = val1.divide(val2, 4, RoundingMode.HALF_UP);

                if (completeValue.compareTo(basicTarget) <= 0) {
                    BigDecimal result = val3.multiply(new BigDecimal(2)).setScale(4, RoundingMode.HALF_UP);
                    return result;
                } else if (completeValue.compareTo(basicTarget) > 0 && completeValue.compareTo(baseline) <= 0) {
                    BigDecimal result = val3.multiply(new BigDecimal(1)).setScale(4, RoundingMode.HALF_UP);
                    return result;
                } else if (completeValue.compareTo(baseline) > 0) {
                    BigDecimal result = val3.multiply(new BigDecimal(-2)).setScale(4, RoundingMode.HALF_UP);
                    return result;
                }
            }
        } catch (Exception e) {
            log.error("error:成本费用占比计分失败！" + e);
        }
        return null;
    }

    /**
     * 融资成本率 完成值 需求说没有档位配置
     * <p>
     * （基准值-完成值）/（基准值*0.05）*具体加减分 写的假的
     *
     * @param businessAudit
     * @param completeValue
     * @param businessAssessment
     * @param gearList
     * @param scoreList
     * @return
     */
    public BigDecimal rzcbValue(String industryCode, BusinessAudit businessAudit, BigDecimal completeValue, BusinessAssessment businessAssessment,
                                List<BusinessAssessmentGear> gearList, List<BusinessAssessmentScore> scoreList) {

        try {
            if (!Objects.isNull(businessAudit)) {
                BigDecimal rate = new BigDecimal(businessAssessment.getScoreStandard()).divide(new BigDecimal(100));
                //激励目标值
                BigDecimal target = businessAudit.getTarget();
                //基本目标值
                BigDecimal basicTarget = businessAudit.getBasicTarget();
                //基准值
                BigDecimal baseline = businessAudit.getBaseline();

                BigDecimal val1 = baseline.subtract(completeValue);
                BigDecimal val2 = baseline.multiply(rate);
                BigDecimal val3 = val1.divide(val2, 4, RoundingMode.HALF_UP);

                if (completeValue.compareTo(basicTarget) <= 0) {
                    BigDecimal result = val3.multiply(new BigDecimal(2)).setScale(4, RoundingMode.HALF_UP);
                    return result;
                } else if (completeValue.compareTo(basicTarget) > 0 && completeValue.compareTo(baseline) <= 0) {
                    BigDecimal result = val3.multiply(new BigDecimal(1)).setScale(4, RoundingMode.HALF_UP);
                    return result;
                } else if (completeValue.compareTo(baseline) > 0) {
                    BigDecimal result = val3.multiply(new BigDecimal(-2)).setScale(4, RoundingMode.HALF_UP);
                    return result;
                }
            }
        } catch (Exception e) {
            log.error("error:融资成本率计分失败！" + e);
        }
        return null;
    }

    /**
     * 有效投资（含重大项目） 计划投资额
     *
     * @param latestPlan
     * @param businessAudit
     * @param completeValue
     * @param businessAssessment
     * @param gearList
     * @param scoreList
     * @return
     */
    public BigDecimal yxtz(String industryCode, BaseInvestmentPlan latestPlan, BusinessAudit businessAudit, BigDecimal completeValue, BusinessAssessment businessAssessment,
                           List<BusinessAssessmentGear> gearList, List<BusinessAssessmentScore> scoreList) {


        //若档位配置为空的话，则默认1列
        Integer index = 1;
        try {
            if (CollectionUtil.isEmpty(gearList)) {
                index = 1;
            } else {
                //找出对应的行业的档位
                Optional<BusinessAssessmentGear> assessmentGearOptional = gearList.stream().filter(e -> e.getIndustryTypeCode().equals(industryCode)).findFirst();
                if (!assessmentGearOptional.isPresent()) {
                    index = 1;
                }
                BusinessAssessmentGear businessAssessmentGear = assessmentGearOptional.get();


                List<BusinessAssessmentGearDynamic> gearDynamicList = businessAssessmentGearDynamicService.list(Wrappers.<BusinessAssessmentGearDynamic>lambdaQuery()
                        .in(BusinessAssessmentGearDynamic::getGearId, gearList.stream().map(BusinessAssessmentGear::getId).collect(Collectors.toList())));

                //计划投资额
                BigDecimal plannedInvestment = latestPlan.getPlannedInvestment();

                List<BusinessAssessmentGearDynamic> currentGearDynamic = gearDynamicList.stream().filter(e -> e.getGearId().equals(businessAssessmentGear.getId())).collect(Collectors.toList());

                // 按照dwIndex属性从小到大排序
                List<BusinessAssessmentGearDynamic> sortedList = currentGearDynamic.stream()
                        .sorted(Comparator.comparingInt(BusinessAssessmentGearDynamic::getDwIndex))
                        .collect(Collectors.toList());

                //经需求确认都是档位一般是区间
                for (BusinessAssessmentGearDynamic businessAssessmentGearDynamic : sortedList) {
                    String dwValueStr = businessAssessmentGearDynamic.getDwValue();
                    if (StringUtil.isNotBlank(dwValueStr)) {
                        String[] split = dwValueStr.split(",");
                        BigDecimal startValue = new BigDecimal(split[0]);
                        BigDecimal endValue = new BigDecimal(split[1]);
                        if (plannedInvestment.compareTo(startValue) >= 0 && plannedInvestment.compareTo(endValue) <= 0) {
                            index = businessAssessmentGearDynamic.getDwIndex();
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("error:有效投资（含重大项目档位计算失败！" + e);
        }

        /**
         * 完成值就是完成率
         */
        try {

            BigDecimal result = BigDecimal.ZERO;
            for (BusinessAssessmentScore businessAssessmentScore : scoreList) {

                String customValue = businessAssessmentScore.getCustomValue();
                String compareTypeCode = businessAssessmentScore.getCompareTypeCode();

                List<BusinessAssessmentScoreDynamic> scoreDynamicsList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                        .eq(BusinessAssessmentScoreDynamic::getScoreId, businessAssessmentScore.getId()).eq(BusinessAssessmentScoreDynamic::getDwIndex, index));

                BusinessAssessmentScoreDynamic businessAssessmentScoreDynamic = scoreDynamicsList.get(0);

                if (StringUtil.isNotBlank(customValue)) {

                    BigDecimal dwValue = StringUtil.isNotBlank(businessAssessmentScoreDynamic.getDwValue()) ? new BigDecimal(businessAssessmentScoreDynamic.getDwValue()) : new BigDecimal(1);

                    if ("171001".equals(compareTypeCode)) {
                        //大于
                        BigDecimal val = new BigDecimal(customValue);
                        if (completeValue.compareTo(val) >= 0) {
                            BigDecimal num = completeValue.subtract(val).multiply(dwValue).setScale(4, RoundingMode.HALF_UP);
                            result = num;
                            break;
                        }
                    } else if ("171002".equals(compareTypeCode)) {
                        //大于
                        BigDecimal val = new BigDecimal(customValue);
                        if (completeValue.compareTo(val) < 0) {
                            BigDecimal num = completeValue.subtract(val).multiply(dwValue).setScale(4, RoundingMode.HALF_UP);
                            result = num;
                            break;
                        }
                    } else if ("171002".equals(compareTypeCode)) {
                        //区间
                        String[] split = customValue.split(",");
                        BigDecimal start = new BigDecimal(split[0]);
                        BigDecimal end = new BigDecimal(split[1]);

                        if (completeValue.compareTo(start) >= 0 && completeValue.compareTo(end) < 0) {
                            BigDecimal subValue = completeValue.subtract(start);
                            BigDecimal num = subValue.multiply(dwValue).setScale(4, RoundingMode.HALF_UP);
                            result = num;
                            break;
                        }
                    }

                }
            }
            return result.multiply(new BigDecimal(100)).setScale(4, RoundingMode.HALF_UP);
        } catch (Exception e) {
            log.error("error:有效投资（含重大项目计分计算失败！" + e);
        }
        return null;
    }

    /**
     * 净资产收益率：基准值分档标准
     * 计分方法和人均归母率一样
     *
     * @param businessAudit      考核国资审核
     * @param businessAssessment 配置主表
     * @param gearList           档位列表
     * @param scoreList          计分列表
     * @return
     */
    public BigDecimal jzcValue(String industryCode, BusinessAudit businessAudit, BigDecimal completeValue, BusinessAssessment businessAssessment,
                               List<BusinessAssessmentGear> gearList, List<BusinessAssessmentScore> scoreList) {
        //档位
        Integer index = getJchIndex(industryCode, gearList, businessAudit);
        try {
            BigDecimal asseRate = new BigDecimal(businessAssessment.getScoreStandard()).divide(new BigDecimal(100));

            if (!Objects.isNull(index)) {
                //基准值
                BigDecimal baseline = businessAudit.getBaseline();
                //基本目标值
                BigDecimal basicTarget = businessAudit.getBasicTarget();
                //激励目标值
                BigDecimal target = businessAudit.getTarget();
                //本年完成值
                BigDecimal complete = completeValue;

                //轨道
                BigDecimal rate = (target.subtract(baseline)).multiply(asseRate).setScale(4, RoundingMode.HALF_UP);

                //动态列
                List<BusinessAssessmentScoreDynamic> scoreDynamicsList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                        .in(BusinessAssessmentScoreDynamic::getScoreId, scoreList.stream().map(BusinessAssessmentScore::getId).collect(Collectors.toList())));

                BigDecimal scoreValue = BigDecimal.ZERO;

                for (BusinessAssessmentScore businessAssessmentScore : scoreList) {
                    //比较类型
                    String compareTypeCode = businessAssessmentScore.getCompareTypeCode();
                    //对比标准
                    String compareStandardCode = businessAssessmentScore.getCompareStandardCode();

                    Integer finalIndex = index;
                    Optional<BusinessAssessmentScoreDynamic> assessmentScoreDynamicOptional = scoreDynamicsList.stream().filter(e -> e.getScoreId().equals(businessAssessmentScore.getId()) && e.getDwIndex().equals(finalIndex)).findFirst();
                    if (assessmentScoreDynamicOptional.isPresent()) {
                        BusinessAssessmentScoreDynamic businessAssessmentScoreDynamic = assessmentScoreDynamicOptional.get();
                        String dwValueStr = businessAssessmentScoreDynamic.getDwValue();
                        BigDecimal dwValue = StringUtil.isNotBlank(dwValueStr) ? new BigDecimal(dwValueStr) : new BigDecimal("1");
                        if ("171001".equals(compareTypeCode)) {
                            //大于 激励目标值
                            if ("172003".equals(compareStandardCode)) {

                                if (complete.compareTo(target) >= 0) {
                                    BigDecimal val = (complete.subtract(target)).divide(rate, 4, RoundingMode.HALF_UP).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                            }


                        } else if ("171002".equals(compareTypeCode)) {
                            //完成值小于基准值
                            if ("172001".equals(compareStandardCode)) {
                                if (complete.compareTo(baseline) <= 0) {
                                    BigDecimal val = (baseline.subtract(complete)).divide(rate, 4, RoundingMode.HALF_UP).add(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    break;
                                }
                            }
                        } else if ("171003".equals(compareTypeCode)) {
                            //完成值大于激励目标值
                            if (complete.compareTo(target) >= 0) {
                                //基本目标值-激励目标值
                                if (compareStandardCode.equals("172002,172003")) {
                                    BigDecimal val = ((target.subtract(basicTarget)).divide(rate, 4, RoundingMode.HALF_UP)).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                                // 基准值-基本目标值
                                if (compareStandardCode.equals("172001,172002")) {
                                    BigDecimal val = ((basicTarget.subtract(baseline)).divide(rate, 4, RoundingMode.HALF_UP)).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                            }
                            //小于激励目标值 大于基本目标值
                            if (complete.compareTo(basicTarget) >= 0 && complete.compareTo(target) <= 0) {
                                //基本目标值-激励目标值
                                if (compareStandardCode.equals("172002,172003")) {
                                    BigDecimal val = ((complete.subtract(basicTarget)).divide(rate, 4, RoundingMode.HALF_UP)).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                                // 基准值-基本目标值-
                                if (compareStandardCode.equals("172001,172002")) {
                                    BigDecimal val = ((basicTarget.subtract(baseline)).divide(rate, 4, RoundingMode.HALF_UP)).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                            }
                            //大于基准值 小于基本目标值
                            if (complete.compareTo(baseline) >= 0 && complete.compareTo(basicTarget) <= 0) {
                                //基准值-基本目标值
                                if (compareStandardCode.equals("172001,172002")) {
                                    BigDecimal val = ((complete.subtract(baseline)).divide(rate, 4, RoundingMode.HALF_UP)).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                            }

                        }

                    }

                }
                return scoreValue.setScale(4, RoundingMode.HALF_UP);
            }
        } catch (Exception e) {
            log.error("error:净资产收益率计分失败：" + e);
        }
        return null;
    }

    /**
     * 获取净资产档位
     *
     * @param gearList
     * @param businessAudit
     * @return
     */
    private int getJchIndex(String industryCode, List<BusinessAssessmentGear> gearList, BusinessAudit businessAudit) {
        //若档位配置为空的话，则默认1列
        Integer index = null;
        try {
            if (CollectionUtil.isEmpty(gearList)) {
                index = 1;
            } else {
                //基准值
                BigDecimal baseline = businessAudit.getBaseline();
                Optional<BusinessAssessmentGear> assessmentGearOptional = gearList.stream().filter(e -> e.getIndustryTypeCode().equals(industryCode)).findFirst();
                if (!assessmentGearOptional.isPresent()) {
                    return index;
                }
                BusinessAssessmentGear businessAssessmentGear = assessmentGearOptional.get();

                List<BusinessAssessmentGearDynamic> gearDynamicList = businessAssessmentGearDynamicService.list(Wrappers.<BusinessAssessmentGearDynamic>lambdaQuery()
                        .in(BusinessAssessmentGearDynamic::getGearId, gearList.stream().map(BusinessAssessmentGear::getId).collect(Collectors.toList())));
                List<BusinessAssessmentGearDynamic> currentGearDynamic = gearDynamicList.stream().filter(e -> e.getGearId().equals(businessAssessmentGear.getId())).collect(Collectors.toList());

                // 按照dwIndex属性从小到大排序
                List<BusinessAssessmentGearDynamic> sortedList = currentGearDynamic.stream()
                        .sorted(Comparator.comparingInt(BusinessAssessmentGearDynamic::getDwIndex))
                        .collect(Collectors.toList());

                //经需求确认都是档位一般是区间
                for (BusinessAssessmentGearDynamic businessAssessmentGearDynamic : sortedList) {
                    String dwValueStr = businessAssessmentGearDynamic.getDwValue();
                    if (StringUtil.isNotBlank(dwValueStr) && !dwValueStr.equals("null,null")) {
                        String[] split = dwValueStr.split(",");
                        BigDecimal startValue = new BigDecimal(split[0]);
                        BigDecimal endValue = new BigDecimal(split[1]);
                        if (baseline.compareTo(startValue) <= 0 && baseline.compareTo(endValue) >= 0) {
                            index = businessAssessmentGearDynamic.getDwIndex();
                        }
                    }
                }

            }
        } catch (Exception e) {
            log.error("error：档位计算失败" + e);
        }
        return index;
    }

    /**
     * 人均归母 档位根据单位
     *
     * @param businessAudit
     * @param completeValue
     * @param businessAssessment
     * @param gearList
     * @param scoreList
     * @return
     */
    public BigDecimal rjgmValue(PerformanceReportDTO dto, BusinessAudit businessAudit, BigDecimal completeValue, BusinessAssessment businessAssessment,
                                List<BusinessAssessmentGear> gearList, List<BusinessAssessmentScore> scoreList) {
        //基准值
        BigDecimal baseline = businessAudit.getBaseline();

        //基本目标值
        BigDecimal basicTarget = businessAudit.getBasicTarget();

        //激励目标值
        BigDecimal target = businessAudit.getTarget();
        //本年完成值
        BigDecimal complete = completeValue;
        try {
            BigDecimal asseRate = new BigDecimal(businessAssessment.getScoreStandard()).divide(new BigDecimal(100));

            Integer index = getRjgmOrgDw(dto);

            if (!Objects.isNull(index)) {
                //轨道
                BigDecimal rate = (target.subtract(baseline)).multiply(asseRate).setScale(4, RoundingMode.HALF_UP).abs();

                //动态列
                List<BusinessAssessmentScoreDynamic> scoreDynamicsList = businessAssessmentScoreDynamicService.list(Wrappers.<BusinessAssessmentScoreDynamic>lambdaQuery()
                        .in(BusinessAssessmentScoreDynamic::getScoreId, scoreList.stream().map(BusinessAssessmentScore::getId).collect(Collectors.toList())));


                BigDecimal scoreValue = BigDecimal.ZERO;
                for (BusinessAssessmentScore businessAssessmentScore : scoreList) {
                    //比较类型
                    String compareTypeCode = businessAssessmentScore.getCompareTypeCode();
                    //对比标准
                    String compareStandardCode = businessAssessmentScore.getCompareStandardCode();

                    Integer finalIndex = index;
                    Optional<BusinessAssessmentScoreDynamic> assessmentScoreDynamicOptional = scoreDynamicsList.stream().filter(e -> e.getScoreId().equals(businessAssessmentScore.getId()) && e.getDwIndex().equals(finalIndex)).findFirst();
                    if (assessmentScoreDynamicOptional.isPresent()) {
                        BusinessAssessmentScoreDynamic businessAssessmentScoreDynamic = assessmentScoreDynamicOptional.get();
                        String dwValueStr = businessAssessmentScoreDynamic.getDwValue();
                        BigDecimal dwValue = StringUtil.isNotBlank(dwValueStr) ? new BigDecimal(dwValueStr) : new BigDecimal("1");
                        if ("171001".equals(compareTypeCode)) {
                            //大于 激励目标值
                            if ("172003".equals(compareStandardCode)) {
                                if (complete.compareTo(target) >= 0) {
                                    BigDecimal val = (complete.subtract(target)).divide(rate, 4, RoundingMode.HALF_UP).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                            }
                        } else if ("171002".equals(compareTypeCode)) {
                            //完成值小于基准值
                            if ("172001".equals(compareStandardCode)) {
                                if (complete.compareTo(baseline) <= 0) {
                                    BigDecimal val = (baseline.subtract(complete)).divide(rate, 4, RoundingMode.HALF_UP).add(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    break;
                                }
                            }
                        } else if ("171003".equals(compareTypeCode)) {
                            //完成值大于激励目标值
                            if (complete.compareTo(target) >= 0) {
                                //基本目标值-激励目标值-
                                if (compareStandardCode.equals("172002,172003")) {
                                    BigDecimal val = ((target.subtract(basicTarget)).divide(rate, 4, RoundingMode.HALF_UP)).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                                // 基准值-基本目标值
                                if (compareStandardCode.equals("172001,172002")) {
                                    BigDecimal val = ((basicTarget.subtract(baseline)).divide(rate, 4, RoundingMode.HALF_UP)).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                            }
                            //小于激励目标值 大于基本目标值
                            if (complete.compareTo(basicTarget) >= 0 && complete.compareTo(target) <= 0) {
                                //基本目标值-激励目标值
                                if (compareStandardCode.equals("172002,172003")) {
                                    BigDecimal val = ((complete.subtract(basicTarget)).divide(rate, 4, RoundingMode.HALF_UP)).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                                // 基准值-基本目标值
                                if (compareStandardCode.equals("172001,172002")) {
                                    BigDecimal val = ((basicTarget.subtract(baseline)).divide(rate, 4, RoundingMode.HALF_UP)).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                            }
                            //大于基准值 小于基本目标值
                            if (complete.compareTo(baseline) >= 0 && complete.compareTo(basicTarget) <= 0) {
                                // 基准值-基本目标值-
                                if (compareStandardCode.equals("172001,172002")) {
                                    BigDecimal val = ((complete.subtract(baseline)).divide(rate, 4, RoundingMode.HALF_UP)).multiply(dwValue);
                                    scoreValue = scoreValue.add(val);
                                    continue;
                                }
                            }

                        }

                    }

                }
                return scoreValue.setScale(4, RoundingMode.HALF_UP);
            }
        } catch (Exception e) {
            log.error("error:人均归母净利润计分失败！" + e);
        }
        return null;
    }
}

